package com.wqj.kyee.gps.bluetooth

import android.os.Handler
import android.os.Message
import android.util.Log
import com.wqj.kyee.gps.nmea.NMEA
import java.io.*


/**
 * Created by kyee on 17-12-8.
 */
public class BtReadThread(mHandler: Handler) : Thread() {
    private val mmInStream: InputStream?
    private val mmOutStream: OutputStream?
    private var mHandler: Handler
    private var runningFlag: Boolean = false
    lateinit var isr: InputStreamReader

    init {
        var tmpIn: InputStream? = null
        var tmpOut: OutputStream? = null
        this.mHandler = mHandler
        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = BtDevicesActivity.connectedSock?.inputStream
            tmpOut = BtDevicesActivity.connectedSock?.outputStream
        } catch (e: IOException) {
        }

        mmInStream = tmpIn
        mmOutStream = tmpOut
    }

    override fun start() {
        if (!BtDevicesActivity.is_bt_connected) {
            Log.e("wqj", "bt is not connected, won't read data")
            return
        }
        if (runningFlag) {
            Log.d("wqj", "thread already start")
            return
        }
        isr = InputStreamReader(`mmInStream`, "UTF-8")
        runningFlag = true
        super.start()
        Log.d("wqj", "thread start")

    }

    var delta = 0.0f
    var deltaD = 0.0f
    override fun run() {
            //bytes = mmInStream!!.read(buffer)
            //将字节流转化成字符流，并指定字符集
            //将字符流以缓存的形式一行一行输出
            val bf = BufferedReader(isr)
            var newLine = ""
            do {
                try {
                    var nmea = NMEA()
                    var gpsPosition = nmea.GPSPosition()

                    newLine = bf.readLine()
                    gpsPosition = nmea.parse(newLine)


                    if ((gpsPosition.lat != 0.0) && (gpsPosition.lon!= 0.0)) {
                        android.util.Log.e("wangrui", gpsPosition.toString());
                        val msg = Message.obtain()
                        msg.obj = gpsPosition
                        msg.what = BtDevicesActivity.GPS_BOARD_DATA
                        if (!runningFlag) {
                            //isr.close()
                            break
                        } else {
                            mHandler.sendMessage(msg)
                        }
                    }

                } catch (e: IOException) {
                    break
                }

            } while (true)

    }

    /* Call this from the main activity to send data to the remote device */
    fun write(bytes: ByteArray) {
        try {
            mmOutStream!!.write(bytes)
        } catch (e: IOException) {
        }

    }

    /* Call this from the main activity to shutdown the connection */
    fun cancel() {
        runningFlag = false

    }
}